import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.dnspod.v20210323 import dnspod_client, models
import get_public_ip
import get_domain_ip





def show_domain_table(table):
    for x in table:
        print("%s:%s"%(x['domain'],x['value']))



def demo_json_secret():
    try:
        secret_json = {'SecretId':'xxx','SecretKey':'xxx'}
        with open('./secret.json',mode='w') as user_file:
            user_file.write(json.dumps(secret_json,sort_keys=True, indent=4, separators=(',', ':')))
    except:
        print("demo secret error")



def demo_domain_table():
    try:
        secret_json = [{'domain':'v.avinfo.fun','value':'public_ip'},{'domain':'abc.avinfo.fun','value':'192.168.1.2'}]
        with open('./domain_table.json',mode='w') as user_file:
            user_file.write(json.dumps(secret_json,sort_keys=True, indent=4, separators=(',', ':')))
    except:
        print("demo domain_table error")



def load_domain_table(path_file='./domain_table.json'):

    try:
        with open(path_file,mode='r') as user_file:
            domain_table = json.load(user_file)
            return domain_table
    except:
        print("load domain table error")
        demo_domain_table()
        return 'xxx','xxx'


#test_table = load_domain_table()
#show_domain_table(test_table)


def load_json_secret_key(path_file='./secret.json'):

    try:
        with open(path_file,mode='r') as user_file:
            parsed_json = json.load(user_file)
            return parsed_json['SecretId'],parsed_json['SecretKey']
    except:
        print("load secret error")
        demo_json_secret()
        return 'xxx','xxx'

    





def make_client(SecretId,SecretKey):
    cred = credential.Credential(SecretId,SecretKey)
    # 实例化一个http选项，可选的，没有特殊需求可以跳过
    httpProfile = HttpProfile()
    httpProfile.endpoint = "dnspod.tencentcloudapi.com"

    # 实例化一个client选项，可选的，没有特殊需求可以跳过
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    # 实例化要请求产品的client对象,clientProfile是可选的
    client = dnspod_client.DnspodClient(cred, "", clientProfile)
    return client



def get_sub_domain_id(client,sub_domain="v",domain= "avinfo.fun"):
    sub_domain_id = 0
    # 实例化一个请求对象,每个接口都会对应一个request对象
    req = models.DescribeRecordListRequest()
    params = {
    "Domain": domain
    }
    req.from_json_string(json.dumps(params))

    # 返回的resp是一个DescribeRecordListResponse的实例，与请求对象对应
    resp = client.DescribeRecordList(req)

    for x in resp.RecordList:
        if(x.Name == sub_domain):
            print("%s:id:%d "%(sub_domain+'.'+domain,x.RecordId))
            sub_domain_id = x.RecordId

    return sub_domain_id



#sub_domain_id = get_sub_domain_id(client)






def show_all_sub_demain(SecretId,SecretKey,domain = "avinfo.fun"):
  
    client = make_client(SecretId,SecretKey)
    # 实例化一个请求对象,每个接口都会对应一个request对象
    req = models.DescribeRecordListRequest()
    params = {
    "Domain": domain
    }
    req.from_json_string(json.dumps(params))

    # 返回的resp是一个DescribeRecordListResponse的实例，与请求对象对应
    resp = client.DescribeRecordList(req)


    # 输出json格式的字符串回包
    print(resp.to_json_string())

#show_all_sub_demain("AKIDkQ0JWnuiR34wwUwGmJiuIZjov0HNn8Vy","jIoFtPHEYs69Tkx0qUw4EneXPHXZgWMM","avinfo.fun")



gparams = {
    "Domain": "avinfo.fun",
    "SubDomain": "v",
    "RecordType": "A",
    "RecordLine": "默认",
    "Value": "1.1.1.1",
    "RecordId": 1398088451
}




def set_sub_domain_ip(client,SubDomain="v",Domain= "avinfo.fun",RecordId=111111111111,user_ip="192.168.1.1"):

    '''params = {
    "Domain": Domain,
    "SubDomain": SubDomain,
    "RecordType": "A",
    "RecordLine": "默认",
    "Value": user_ip,
    "RecordId":  RecordId 
    }'''
 
    params = {
    "Domain": Domain,
    "SubDomain": SubDomain,
    "RecordType": "A",
    "RecordLine": "默认",
    "Value": user_ip,
    "RecordId": RecordId
    }



    try:
        req = models.ModifyRecordRequest()
        req.from_json_string(json.dumps(params))
        resp = client.ModifyRecord(req)
    except TencentCloudSDKException as err:
        print(err)








if __name__ == "__main__":
   
    gSecretId=''
    gSecretKey=''
    
    #gSecretId,gSecretKey = load_json_secret_key("/home/ubuntu/ddns/secret.json")
    #gdomain_table = load_domain_table("/home/ubuntu/ddns/domain_table.json")


    gSecretId,gSecretKey = load_json_secret_key("./secret.json")
    gdomain_table = load_domain_table("./domain_table.json")
    user_public_ip = get_public_ip.get_local_public_ip()

    client = make_client(gSecretId,gSecretKey)


    for x in gdomain_table:
        now_domain_ip = get_domain_ip.domain_to_ip(x['domain'])
        SubDomain,Domain, = x['domain'].split('.',1)
        RecordId = get_sub_domain_id(client,SubDomain,Domain)

        
        if x['value'] == 'public_ip':
            if(user_public_ip.decode('utf-8') == now_domain_ip):
                print("not need update")
            else:
                set_sub_domain_ip(client,SubDomain,Domain,RecordId,str(user_public_ip,'utf-8'))

        else:
            if(x['value'] == now_domain_ip):
                print("not need update")
            else:
                set_sub_domain_ip(client,SubDomain,Domain,RecordId,x['value'])





            



















